import Vue from 'vue'
import _ from "lodash"

// 千分位
Vue.directive('rate', {
  bind (el, binding, vnode) {

    const key = Object.keys(binding.modifiers)[0]
    if (!binding.value[key]) {
      binding.value[key] = "0"
    }
    // 处理百分位展示
    const generatingThousandthPer = (num) => {
      return _.multiply(num, 100) + "%"
    }
    // 赋值
    const assignment = (event, value, value2) => {
      binding.value[key] = value;
      vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value2 || value))
    }
    // 处理最后一位非法字符
    const handlerIllegalStr = (str) => {
      while (!(/^[0-9]+.?[0-9]*/.test(str.charAt(str.length - 1)))) {
        str = str.substr(0, str.length - 1)
      }
      return str
    }


    const input = el.querySelector("input")

    if (input) {

      input.setAttribute("data-rate", binding.value[key]);
      vnode.context.$nextTick(() => input.value = generatingThousandthPer(binding.value[key]))

      input.addEventListener("blur", (event) => {
        const val = event.target.value;
        // 是否是数字
        if (!val || isNaN(val) || Number(val) > 1 || Number(val) < 0) {
          /**
           * 如果不是数字 重置为原数据
           */
          const value = input.getAttribute("data-rate");
          binding.value[key] = value.replace(/%/g, "")
          vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value))
          return false;
        }
        input.setAttribute("data-rate", val);
        assignment(event, handlerIllegalStr(val.replace(/%/g, "")))
      })

      input.addEventListener("focus", (event) => {
        const value = input.getAttribute("data-rate");
        const inp = event.target.value = value.replace(/%/g, "")
      })
    }
  }
});